<template>
  <Modal v-model="visible"
         title="密码修改"
         :closable="false"
         :mask-closable="false">
    <Form ref="dataForm" :model="dataForm" :rules="ruleValidate" :label-width="80">
      <FormItem label="旧密码" prop="password">
        <Input v-model="dataForm.password" type="password" placeholder="输入旧密码" clearable></Input>
      </FormItem>
      <FormItem label="新密码" prop="newPassword">
        <Input v-model="dataForm.newPassword" type="password" placeholder="输入新密码" clearable></Input>
      </FormItem>
      <FormItem label="确认密码" prop="confirmPassword">
        <Input v-model="dataForm.confirmPassword" type="password" placeholder="输入确认密码" clearable></Input>
      </FormItem>
    </Form>
    <div slot="footer">
      <Button type="text" @click="handleCancel">取消</Button>
      <Button type="primary" :loading="showLoading" @click="handleSubmit">保存</Button>
    </div>
  </Modal>
</template>

<script>
export default {
  name: 'password-update',
  data () {
    let validateConfirmPassword = (rule, value, callback) => {
      if (this.dataForm.newPassword !== value) {
        callback(new Error('确认密码与新密码不一致'))
      } else {
        callback()
      }
    };
    return {
      /**/
      visible: false,
      showLoading: false,
      dataForm: {
        password: '',
        newPassword: '',
        confirmPassword: ''
      },
      ruleValidate: {
        password: [
          { required: true, message: '旧密码不能为空', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '新密码不能为空', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init (id) {
      this.$refs['dataForm'].resetFields();
      this.visible = true;
    },
    handleCancel () {
      this.visible = false;
      this.showLoading = false;
    },
    handleSubmit () { // 表单提交
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.showLoading = true;
          this.$http({
            url: this.$http.adornUrl('/sys/user/password'),
            method: 'post',
            data: this.$http.adornData({
              'password': this.dataForm.password,
              'newPassword': this.dataForm.newPassword
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$Message.success({
                content: '操作成功',
                duration: 2,
                onClose: () => {
                  this.handleCancel();
                }
              })
            } else {
              this.$Message.error(data.msg);
              this.showLoading = false;
            }
          })
        }
      })
    }
  }
}
</script>
